var RoleManager = function() {
	this.table;
	this.form;
	this.roleTable;
	this.formSelects;
};
RoleManager.prototype = {
	init : function(table, form, layer, formSelects) {
		this.table = table;
		this.form = form;
		this.layer = layer;
		this.formSelects = formSelects;

		this.initRender();
		this.initEvent();
	},
	initRender : function() {
		this.roleTable = this.table.render({
			id : "roletable",
			elem : '#allRole',
			height : 'full-215',
			url : '/roles/queryAllRole', // 数据接口
			page : true, // 开启分页
			limit : 10,
			cellMinWidth : 80,
			even : true,
			toolbar:'#roleTopTool',
			cols : [ [ // 表头
			{
				type : 'checkbox',
				fixed : 'left',
			},{
				field : 'name',
				title : '角色名',
				sort : true
			},{
				field : 'create_time',
				title : '创建时间',
				sort : true
			},{
				field : 'update_time',
				title : '修改时间',
				sort : true
			},{
				title : '操作',
				toolbar : '#roleToolbar'
			} ] ],
			response : {
				statusName : 'status', // 数据状态的字段名称，默认：code
				statusCode : 200, // 成功的状态码，默认：0
				msgName : 'message', // 状态信息的字段名称，默认：msg
				countName : 'total', // 数据总数的字段名称，默认：count
				dataName : 'data', // 数据列表的字段名称，默认：data
			},
			loading : true
		});
	},
	initEvent : function() {
		var that = this;
		// 监听工具条
		that.table.on('tool(allRole)', function(obj) {
			var data = obj.data;
			if (obj.event === 'del') {
				layer.confirm('确定删除角色"' + data.name + '"？', function(index) {
					that.deleteRole(obj);
					that.layer.close(index);
				});
			} else if (obj.event === 'edit') {
				that.editRole(obj);
			}else {
				return;
			}
		});

		var $ = layui.$, active = {
			addRole : function() { // 获取选中数据
				that.addRole();
			},
			deleteRole : function() { // 获取选中数目
				var checkStatus = that.table.checkStatus('roletable');
				var data = checkStatus.data;
				if (data.length > 0) {
					var ids = [];
					$.each(data, function(i, item) {
						ids.push(item.value);
					});
					that.layer.confirm("确定删除选中的用户？", function(index) {
						that.deleteSeletedRole(ids, data);
						that.layer.close(index);
					});
				} else {
					that.layer.alert("没有选择要删除的角色");
				}

			},
			flushRole : function() {
				that.roleTable.reload({
					loading : true
				});
			}
		};

		that.table.on('toolbar(allRole)', function(obj){
			var type = obj.event;
			active[type] ? active[type].call(this) : '';
		});
	},
	addRole : function() {
		var that = this;
		var html = getHtml("/system/addRole.html");
		var index = layer.open({
			id : "addRole",
			title : "新增角色",
			type : 1,
			content : html,
			area : [ '450px', '220px' ]
		});
		that.initSelect();
		that.eventAddRole(index);

		$("#addrole_cancel").click(function() {
			that.layer.close(index);
			return false;
		});
	},
	eventAddRole : function(index) {
		var that = this;
		that.form.on('submit(addrole_ok)', function(data) {
			data.field.status = 1;
			var param = that.covertData(data);
			that.layer.close(index);
			var loadindex = that.layer.load(0);
			$.ajax({
				url : '/roles/add',
				type : "post",
				dataType : "json",
				contentType: "application/json;charset=UTF-8",
				data : JSON.stringify(param),
				success : function(response) {
					that.layer.close(loadindex);
					var status = response.status;
					if (status == 200) {
						that.roleTable.reload({
							loading : true
						});
					} else {
						that.layer.alert(response.message);
					}
				},
				error : function(xhr, textStatus) {
					that.layer.close(loadindex);
					that.layer.alert(textStatus);
				}
			});
			return false;
		});
	},
	deleteRole : function(obj) {
		var that = this;
		var loadindex = that.layer.load(0);
		$.ajax({
			url : "/roles/delete?id=" + obj.data.value,
			type : "get",
			dataType : "json",
			success : function(response) {
				that.layer.close(loadindex);
				var status = response.status;
				if (status == 200) {
					obj.del();
				} else {
					that.layer.alert(response.message);
				}
			},
			error : function(xhr, textStatus) {
				that.layer.close(loadindex);
				that.layer.alert(textStatus);
			}
		});
	},
	deleteSeletedRole : function(ids, data) {
		var that = this;
		var loadindex = that.layer.load(0);
		$.ajax({
			url : "/roles/deleteRole",
			type : "post",
			dataType : "json",
			contentType: "application/json;charset=UTF-8",
			data : JSON.stringify(ids),
			success : function(response) {
				that.layer.close(loadindex);
				var status = response.status;
				if (status == 200) {
					that.roleTable.reload({
						loading : true
					})
				} else {
					that.layer.alert(response.message);
				}
			},
			error : function(xhr, textStatus) {
				that.layer.close(loadindex);
				that.layer.alert(textStatus);
			}
		});
	},
	editRole : function(obj) {
		var that = this;
		var data = obj.data;
		var html = getHtml("/system/editRole.html");
		var index = layer.open({
			id : "editRole",
			title : "修改" + data.name,
			type : 1,
			content : html,
			area : [ '450px', '220px' ]
		});
		
		that.initSelect(data);
		
		if(data.value == 1){
			$("#editRole input[name='roledesc']").attr("disabled",true)
		}
		$("#editRole input[name='roledesc']").val(data.name);
		that.form.render();
		that.eventEditRole(obj, index);

		$("#editrole_cancel").click(function() {
			that.layer.close(index);
			return false;
		});
	},
	initSelect:function(data){
		var that = this;
		var defvalarr = [];
		if(data){
			var menuid = data.menuid;
			var idarr = menuid.split(",");
			
			$.each(idarr,function(index,id){
				 var defval = id.substring(0,4) + '/' + id;
				 defvalarr.push(defval);
			});
		}
		this.formSelects.config('rolemenu', {
            beforeSuccess: function(id, url, searchVal, result){
                return result.data; 
            },
            success:function(id, url, val, result){
            	that.formSelects.value('rolemenu', defvalarr);
            },
            type:'POST'
        }).data('rolemenu', 'server', {
        	url: '/product/queryAll',
        	linkage: true
        });
		
		
	},
	eventEditRole : function(obj, index) {
		var that = this;
		var id = obj.data.value;
		that.form.on('submit(editrole_ok)', function(data) {
			data.field.id = id;
			var param = that.covertData(data);
			that.layer.close(index);
			var loadindex = that.layer.load(0);
			$.ajax({
				url : '/roles/update',
				type : "post",
				dataType : "json",
				contentType: "application/json;charset=UTF-8",
				data : JSON.stringify(param),
				success : function(response) {
					that.layer.close(loadindex);
					var status = response.status;
					if (status == 200) {
						that.roleTable.reload({
							loading : true
						});
					} else {
						that.layer.alert(response.message);
					}
				},
				error : function(xhr, textStatus) {
					that.layer.close(loadindex);
					that.layer.alert(textStatus);
				}
			});
			return false;
		});
	},
	covertData:function(data){
		var field = data.field;
		var productIds = [];
		var menuIds = [];
		var idArr = this.formSelects.value('rolemenu', 'val'); 
		$.each(idArr,function(index,id){
			var ids = id.split("/");
			var productId = ids[0];
			if(productIds.indexOf(productId) == -1){
				productIds.push(productId);
			}
			menuIds.push(ids[1]);
		});
		field.menuIds = menuIds.join(",");
		field.productIds = productIds.join(",");

		return field;
	}
}